#pragma once
#include <sys/epoll.h>
#include <cstdio>
#include <set>
#include <cstdlib>
#include "Log copy.hpp"

namespace EpollModule
{
    using namespace LogModule;
    static const int epoll_size = 1024;
    class Epoll
    {
    public:
        Epoll(int epollsize = epoll_size) : _max_size(0)
        {
            _epollfd = epoll_create(epollsize);
            if (_epollfd < 0)
            {
                perror("epoll modle creates faied");
                exit(1);
            }
            
        }

        int Epollfd()
        {
            return _epollfd;
        }

        bool AddEpollEvent(int socket, uint32_t event)
        {
            _fd_list.insert(socket);

            epoll_event evt;
            evt.data.fd = socket;
            evt.events = event;
            logger(LogLevel::DEBUG, __FILE__, __LINE__) << "AddEpollEvent:";
            int n = epoll_ctl(_epollfd, EPOLL_CTL_ADD, socket, &evt);
            if (n < 0)
            {
                logger(LogLevel::DEBUG, __FILE__, __LINE__) << "Add failed :";
                return false;
            }
            _max_size += 1;
            return true;
        }

        bool ModEpollEvent(int socket, uint32_t event)
        {
            epoll_event evt;
            evt.data.fd = socket;
            evt.events = event;
            int n = epoll_ctl(_epollfd, EPOLL_CTL_MOD, socket, &evt);
            if (n < 0)
            {
                perror("Failed in modify:");
                return false;
            }
            return true;
        }

        bool DelEpollEvent(int socket)
        {
            _fd_list.erase(socket);

            int n = epoll_ctl(_epollfd, EPOLL_CTL_DEL, socket, nullptr);
            if (n < 0)
            {
                perror("Failed in Deleting");
                return false;
            }
            _max_size -= 1;
            return true;
        }

        int WaitEpollEvent(epoll_event *out)
        {
            int n = epoll_wait(_epollfd, out, 1024, 1000);
            if (n < 0)
            {
                perror("Epoll wait: ");
                return -1;
            }
            else if (n == 0)
            {
                std::cout << "此次事件监控没有检测到数据！"<<std::endl;
                return 0;
            }
            else
            {
                return n;
            }
        }

        void DebugFdList()
        {
            std::cout << "----------fd list is : ------------------" << std::endl;
            for (auto &fd : _fd_list)
            {
                std::cout << fd << " ";
            }
            std::cout << std::endl;
        }

    private:
        int _epollfd;
        int _max_size;
        std::set<int> _fd_list;
    };
}
